home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3398 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  56 lines

  1. Path: ceas.rochester.edu!usenet
  2. From: Lixin Pang <pang>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: using MALLOC() w/ 2-d arrays
  5. Date: 28 Jan 1996 17:16:47 GMT
  6. Organization: University of Rochester School of Engineering and Applied Science
  7. Message-ID: <4egb20$c62@bilbo.ceas.rochester.edu>
  8. References: <4e9nm2$nna@cville-srv.wam.umd.edu> <3108F478.1831@cmt.lpr.mail.carel.fi>
  9. NNTP-Posting-Host: leonardo.me.rochester.edu
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.1N (X11; I; IRIX 5.3 IP22)
  14. X-URL: news:3108F478.1831@cmt.lpr.mail.carel.fi
  15.  
  16. A dynamic 2D array can be obtained as following,
  17.  
  18. --
  19.  
  20. #include <stdio.h>
  21. #include <stdlib.h>    /* for exit() */
  22.     
  23.    double** 2DArray = NULL;
  24.  
  25.    /* Pointer to "num_of_rows" pointers of double */
  26.    2DArray =(double**) malloc( num_of_rows * sizeof(double*) );
  27.    if (!2DArray)
  28.    {
  29.       printf("Cannot allocate memory for 2d array!\n");
  30.       exit(EXIT_FAILURE);
  31.    }
  32.  
  33.    for (i=0; i<num_of_rows; i++)
  34.    {
  35.       /* Each 2DArray[i] is a pointer to "num_of_cols" doubles */
  36.       2DArray[i] = (double*) malloc( num_of_cols * sizeof(double) );
  37.       if(!2DArray[i])
  38.       {
  39.          printf("Cannot allocate memory for 2d array!\n");
  40.          exit(EXIT_FAILURE);
  41.       }
  42.    }
  43.  
  44.    Now 2DArray can be accessed as 2DArray[i][j].  You can specify 
  45.    num_of_rows and num_of_cols at run time.
  46.  
  47. HTH,
  48.  
  49. Lixin
  50. ____________________________________
  51. Department of Mechanical Engineering
  52. University of Rochester
  53. Rochester, NY 14627
  54. ____________________________________
  55.  
  56.